package com.zhengb.nettydemos.chapter3.simple;

import com.zhengb.nettydemos.utils.SerializeUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by zhengbo on 2019/4/2.
 */
public class RemoteServerHandler extends ChannelHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(RemoteServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] request = new byte[byteBuf.readableBytes()];

        byteBuf.readBytes(request);

        DataTransRequestDTO dataTransRequestDTO = SerializeUtil.deserialize(request, DataTransRequestDTO.class);
        if (dataTransRequestDTO == null) {
            logger.error("服务端解析请求失败");
            return;
        }
        logger.info("收到客户端请求,data:{}", dataTransRequestDTO);
        RemoteFunctions remoteFunctions = new RemoteFunctions();
        ResponseDTO responseDTO = remoteFunctions.dealWithData(dataTransRequestDTO);
        ByteBuf response = Unpooled.copiedBuffer(SerializeUtil.serialize(responseDTO));

        ctx.write(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
